package com.byxy.controller;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.byxy.entity.User;
import com.byxy.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;

	/** 登录 */
	@GetMapping("toLoginPage.do")
	public String toLogin() {
		return "login";
	}

	/** 登录 
	 *
	 * */
	@PostMapping("userLogin.do")
	public String doLogin(String userName, String userPassword, String tipId,HttpSession session,Model model,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		//1、创建Subject
		Subject subject = SecurityUtils.getSubject();
		//2、创建token
		UsernamePasswordToken token = new UsernamePasswordToken(userName,userPassword);
		try {
			//3、登录方法
			subject.login(token);
			User user = (User) subject.getPrincipal();
			session.setAttribute("USER", user);
			session.removeAttribute("error");
			return "redirect:toMainPage.do";
		}catch (UnknownAccountException e) {
			session.setAttribute("error", "用户不存在");
			return "redirect:toLoginPage.do";
		} catch (IncorrectCredentialsException e) {
			session.setAttribute("error", "密码不正确");
			return "redirect:toLoginPage.do";
		}
		
//		User u = userService.getByNameAndPassword(userName, userPassword);
//		if (u == null) {
//			session.setAttribute("error", "用户名或密码有误！");
//			return "redirect:toLoginPage.do";
//		} else {
//			session.removeAttribute("error");
//			u.setUserPassword("");
//			session.setAttribute("USER", u);
//			return "redirect:toMainPage.do";
//		}
	}
	
//	退出登录
	@GetMapping("userSignOut.do")
	public String logout(HttpSession session) {
		session.removeAttribute("USER");
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:toMainPage.do";
	}
	
	/** 注册 */
	@GetMapping("toSignUpPage.do")
	public String toSignUpPage(String error, Model model) {
		if (error != null) {
			model.addAttribute("error", "用户名已存在注册失败");
		}
		return "signUp";
	}
	
	/** 注册 */
	@PostMapping("userSignUp.do")
	public String userSingUp(User user, HttpServletRequest req) {
		User result = userService.getByName(user.getUserName());
		if (result != null) {
			return "signUp";
		} else {
			userService.signUp(user);
			return "redirect:toLoginPage.do";
		}
	}
	
}
